package com.kaifamiao.tcp;
import java.io.*;
import java.net.*;

public class FolderServer {
    private static final int PORT = 12345;
    private static final String SAVE_PATH = "/Users/linrui/b/";

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("Server started. Waiting for connection...");
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected!");

            receiveFiles(clientSocket, SAVE_PATH);

            clientSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void receiveFiles(Socket socket, String savePath) throws IOException {
        DataInputStream dis = new DataInputStream(socket.getInputStream());

        int fileCount = dis.readInt();
        for (int i = 0; i < fileCount; i++) {
            String relativePath = dis.readUTF();
            long fileSize = dis.readLong();

            File file = new File(savePath + relativePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            try (FileOutputStream fos = new FileOutputStream(file)) {
                byte[] buffer = new byte[4096];
                long bytesRead = 0;
                while (bytesRead < fileSize) {
                    int read = dis.read(buffer, 0, (int) Math.min(buffer.length, fileSize - bytesRead));
                    fos.write(buffer, 0, read);
                    bytesRead += read;
                }
            }
            System.out.println("Received: " + relativePath);
        }
    }
}
